package com.hh.releasenode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.releasenode.bean.RedisBean;
import com.hh.releasenode.dao.SysUserDao;
import com.hh.releasenode.dto.SysUserDTO;
import com.hh.releasenode.entity.SysUserEntity;
import com.hh.releasenode.exception.RNException;
import com.hh.releasenode.form.SysUserForm;
import com.hh.releasenode.form.UpdateSysUserForm;
import com.hh.releasenode.service.SysUserService;
import com.hh.releasenode.utils.Constant;
import com.hh.releasenode.utils.EncryptionUtils;
import com.hh.releasenode.utils.RandomStrUtils;
import com.hh.releasenode.utils.RegUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @ClassName SysUserServiceImpl
 * @Description 系统用户 service实现类
 * @Author KunxianLi
 * Date 2020/6/12 16:19
 * Version 1.0
 **/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    @Resource
    private SysUserDao sysUserDao;

    @Autowired
    private RedisBean redisBean;

    @Override
    public void registerUser(SysUserForm userForm) {
        //验证是否已存在用户名
        if(!isRightUserName(userForm.getUserName(),null)){
            throw new RNException("用户名已存在");
        }
        //验证手机号
        if(!isRightMobile(userForm.getMobile())){
            throw new RNException("手机号不合法");
        }
        //保存用户
        SysUserEntity entity = new SysUserEntity();
        BeanUtils.copyProperties(userForm,entity);
        String salt = RandomStringUtils.randomAlphabetic(20);
        entity.setSalt(salt);

        entity.setStatus(Constant.SysUserStatus.ENABLE.getValue());
        entity.setPassword(EncryptionUtils.getSha256Hash(userForm.getPassword(),salt));

        //默认角色
        this.save(entity);

    }

    /**
     * @Author KunxianLi
     * @Description 检查用户登陆
     * @Date 2020/6/30 15:05
     * @Param [nameOrMobile, password]
     * @return void
     **/
    @Override
    public String login(String username, String password) {
        LambdaQueryWrapper<SysUserEntity> query = new LambdaQueryWrapper<>();
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new RNException("用户名密码不能为空");
        }
        query.eq(SysUserEntity::getUserName,username);
        SysUserEntity sysUserEntity = this.baseMapper.selectOne(query);
        if(sysUserEntity == null){
            throw new RNException("不存在该用户");
        }

        if(!EncryptionUtils.getSha256Hash(password,sysUserEntity.getSalt()).equals(sysUserEntity.getPassword())){
            throw new RNException("密码错误");
        }

        if(sysUserEntity.getStatus() == 1 ){
            throw new RNException("该账号已禁用，请联系管理员");
        }

        //生成token并缓存
        String token = RandomStrUtils.generateToken("my", null);
        return token;
//        //token有效期2小时
//        redisBean.set(token,sysUserEntity,60*60*2);

    }

    @Override
    public void logout(String token) {
        //删除redis缓存
        redisBean.del(token);

    }

    /**
     * @Author KunxianLi
     * @Description 根据过滤条件分页查询系统用户列表
     * @Date 2020/8/7 15:22
     * @Param [page, params]
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.hh.releasenode.dto.SysUserDTO>
     **/
    @Override
    public Page<SysUserDTO> getSysUserPage(Page<SysUserDTO> page, Map<String,Object> params) {
        return this.baseMapper.getSysUserPage(page,params);
    }


    @Override
    public void updateUserInfo(@RequestBody UpdateSysUserForm form) {

        //获取用户
        SysUserEntity sysUserEntity = this.baseMapper.selectById(form.getId());

        if(null == sysUserEntity){
            throw new RNException("未找到指定用户");
        }

        if(!isRightUserName(form.getUserName(),sysUserEntity.getId())){
            throw new RNException("用户名已存在");
        }
        SysUserEntity entity = new SysUserEntity();
        BeanUtils.copyProperties(form,entity);
        this.updateById(entity);

    }


    /**
     * @Author KunxianLi
     * @Description 验证用户名合法性
     * @Date 2020/6/29 16:56
     * @Param [userName]
     * @return boolean
     **/
    private boolean isRightUserName(String userName,Long id){

        SysUserEntity user = sysUserDao.findByUserName(userName);
        if(user != null){
            return user.getId()==id ? true : false;
        }
        return true;
    }

    private boolean isRightMobile(String mobile){
        if(StringUtils.isBlank(mobile)){
            return true;
        }

        if(RegUtils.isRightMobile(mobile)){
            SysUserEntity user = sysUserDao.findByMobile(mobile);
            if(user == null){
                return true;
            }
        }

        return false;

    }

}
